﻿using A.M.ETO;
using A.M.Joint_Search;
using A.M.Storage.Application;
using A.M.Storage.I_Infrastruecure;
using AutoMapper;
using AutoMapper.Configuration.Conventions;
using DotNetCore.CAP;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using O.M.Production.Domain.Entity;
using Public_Class_Library;
using Redis_ClientInfor;
using SqlSugar;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Net.WebSockets;
using System.Numerics;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using W.M.Materiel.Application.DTO;
using W.M.Materiel.Application.IServices;
using W.M.Materiel.Domain.Entity;
using W.M.Materiel.Infrastruecure.DTO;
using W.M.Materiel.Infrastruecure.IRepository;
using W.M.Materiel.Infrastruecure.Repository;
using Yitter.IdGenerator;

namespace W.M.Materiel.Application.Services
{
    public class Bom_management_tableServices : BaseServices<bom_management_table, string>, IBom_management_tableServices
    {
        private readonly IBom_management_tableRepository bom_Management_TableRepository;
        private readonly ISqlSugarClient sqlSugarClient;
        private readonly ICapPublisher capPublisher;
        private readonly Cross_service_Helper cross_Service_Helper;
        private readonly IBom_item_relation_tableRepository bom_item_relation_TableRepository;
        private readonly IBom_process_relationship_tableRepository bom_process_relationship_TableRepository;
        private readonly IMapper mapper;

        public Bom_management_tableServices(IBom_management_tableRepository bom_Management_TableRepository, ISqlSugarClient sqlSugarClient, ICapPublisher capPublisher, Cross_service_Helper cross_Service_Helper, IMapper mapper, IBom_item_relation_tableRepository bom_item_relation_TableRepository, IBom_process_relationship_tableRepository bom_process_relationship_TableRepository) : base(bom_Management_TableRepository)
        {
            this.bom_Management_TableRepository = bom_Management_TableRepository;
            this.sqlSugarClient = sqlSugarClient;
            this.capPublisher = capPublisher;
            this.cross_Service_Helper = cross_Service_Helper;
            this.mapper = mapper;
            this.bom_item_relation_TableRepository = bom_item_relation_TableRepository;
            this.bom_process_relationship_TableRepository = bom_process_relationship_TableRepository;
        }


        /// <summary>
        /// 添加Bom
        /// </summary>
        /// <param name="c">BOM实体</param>
        /// <returns>统一返回格式</returns>
        public async Task<ApiReturn<string>> AddInfo(BOM_TableDTO c)
        {
            try
            {
                bom_Management_TableRepository.BeginTranInfor();

                ApiReturn<string> apiReturn = new ApiReturn<string>();
                var slist = mapper.Map<bom_management_table>(c);

                List<bom_item_relation_table> materiel = new List<bom_item_relation_table>();

                foreach (var item in c.Bill_of_materialsDTO)
                {
                    bom_item_relation_table bom_item_relation_table = new bom_item_relation_table();
                    bom_item_relation_table.bom_indicates_relationship_id = YitIdHelper.NextId().ToString();
                    bom_item_relation_table.bom_number = c.bom_number;
                    bom_item_relation_table.product_material_numbers = item.material_code;
                    bom_item_relation_table.number_parts = item.number_parts;
                    bom_item_relation_table.attrition_rate = item.attrition_rate;
                    bom_item_relation_table.TimeNum = c.daily_output;
                    materiel.Add(bom_item_relation_table);
                }



                List<bom_process_relationship_table> Processflow = new List<bom_process_relationship_table>();
                foreach (var item in c.prcessDTO)
                {
                    bom_process_relationship_table bom_process_relationship_table = new bom_process_relationship_table();
                    bom_process_relationship_table.bom_process_id = YitIdHelper.NextId().ToString();
                    bom_process_relationship_table.bom_number = c.bom_number;
                    bom_process_relationship_table.process_number = item.process_flow_id;
                    Processflow.Add(bom_process_relationship_table);
                }



                var res1 = cross_Service_Helper.Get("http://10.31.59.5:5123/api/Approval_form/GetShowSystem").Result;
                var geinfor = JsonConvert.DeserializeObject<List<GoarderDTO>>(res1);
                //判断审批状态是否开启
                var xiaos = geinfor.Where(c => c.approval_name == "销售系统").FirstOrDefault();

                if (xiaos.approval_on_no)
                {
                    //如果为开启状态存入Redis中
                    RedisClient.redisClient.HsetInforAsync("nmsc", c.bom_number, slist);
                    RedisClient.redisClient.HsetInforAsync("Gnmsc", c.bom_number, materiel);
                    RedisClient.redisClient.HsetInforAsync("Gnmsced", c.bom_number, Processflow);
                    //添加成功需要传一个消息队列  传递哪个模块 还有编号
                    apiReturn.Code = 300;
                    apiReturn.Message = "等待审批，审批后自动执行";
                    return apiReturn;
                }
                else
                {
                    await bom_Management_TableRepository.AddInfor_Async(slist);
                    var list = await bom_process_relationship_TableRepository.AddInfor_Batch_Async(Processflow);
                    var res = await bom_item_relation_TableRepository.AddInfor_Batch_Async(materiel);
                    apiReturn.Code = 200;
                    apiReturn.Message = "添加成功!";

                    //添加成功需要传一个消息队列 传递哪个模块 还有编号
                    string numberName = "BOM系统-" + c.bom_number;
                    capPublisher.Publish("GetNewNumber", numberName);
                    bom_Management_TableRepository.CommitTranInfor();
                }
                return apiReturn;
            }
            catch (Exception)
            {
                bom_Management_TableRepository.RollbackTranInfor();
                throw;
            }

        }

        public async Task<ApiReturn<string>> GetAddXsInfor(string? id)
        {
            ApiReturn<string> apiReturn = new ApiReturn<string>();
            var rew = await RedisClient.redisClient.HgetInforAsync<bom_management_table>("nmsc", id);
            
            var res1 = await RedisClient.redisClient.HgetInforAsync<List<bom_item_relation_table>>("Gnmsced", id);
            var res2 = await RedisClient.redisClient.HgetInforAsync<List<bom_process_relationship_table>>("Gnmsc", id);
            await bom_Management_TableRepository.AddInfor_Async(rew);
            var res = await bom_item_relation_TableRepository.AddInfor_Batch_Async(res1);
            var list = await bom_process_relationship_TableRepository.AddInfor_Batch_Async(res2);
            if (res > 0)
            {
                apiReturn.Code = 200;
                apiReturn.Message = "添加成功";
            }
            return apiReturn;

        }


        /// <summary>
        /// 显示BOM信息+查询
        /// </summary>
        /// <param name="pageSize">当前页</param>
        /// <param name="pageIndex">页容量</param>
        /// <param name="name">查询条件:成品名称</param>
        /// <returns>统一返回格式</returns>
        public List<Product_BOMDTO> GetBOMrelation(int pageSize, int pageIndex, string? number, out int totalCount, out int pageCount)
        {
            return bom_Management_TableRepository.GetBOMrelation(pageSize, pageIndex, number, out totalCount, out pageCount);
        }

        /// <summary>
        /// 显示BOM详情
        /// </summary>
        /// <param name="id">BOM编号</param>
        /// <returns></returns>
        public List<Details> GetProduct_BOMDTOs(string? id)
        {
            return bom_Management_TableRepository.GetProduct_BOMDTOs(id);
        }

        /// <summary>
        /// 工艺流程详细
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<CreatedInfoDTO> GetCreatedinfos(string? id)
        {
            return bom_Management_TableRepository.GetCreatedinfos(id);
        }

        /// <summary>
        /// 显示
        /// </summary>
        /// <returns></returns>
        public List<Product_BOMDTO> GetBOMrelations()
        {
            return bom_Management_TableRepository.GetBOMrelations();
        }

        /// <summary>
        /// 删除单个BOM信息
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public async Task<ApiReturn<int>> DeleteBOM(string? c)
        {
            try
            {
                bom_Management_TableRepository.BeginTranInfor();
                ApiReturn<int> apiReturn = new ApiReturn<int>();

                //删主表
                var res = await bom_Management_TableRepository.GetShowObjAsync(a => a.bom_number == c);
                var list = await bom_Management_TableRepository.DelInfor_Async(res);

                //删除第二张表
                var res2 = (await bom_item_relation_TableRepository.GetShowQueryableAsync(x => x.bom_number == res.bom_number)).ToList();
                if (res2.Count() != 0)
                {
                    await bom_item_relation_TableRepository.DelInfor_Batch_Async(res2);

                }

                //删除第三张表
                var res3 = (await bom_process_relationship_TableRepository.GetShowQueryableAsync(x => x.bom_number == res.bom_number)).ToList();
                if (res3.Count() != 0)
                {
                    await bom_process_relationship_TableRepository.DelInfor_Batch_Async(res3);
                }
                bom_Management_TableRepository.CommitTranInfor();
                apiReturn.Code = 200;
                apiReturn.Message = "删除成功!";
                return apiReturn;
            }
            catch (Exception)
            {
                bom_Management_TableRepository.RollbackTranInfor();
                throw;
            }
        }

        /// <summary>
        /// 修改BOM信息
        /// </summary>
        /// <param name="c">BOM实体</param>
        /// <returns>统一返回格式</returns>
        public async Task<ApiReturn<string>> GetUpdateBOM(Bom_management_tableDTO c)
        {
            ApiReturn<string> apiReturn = new ApiReturn<string>();
            var res = await bom_Management_TableRepository.GetShowInforAsync(x => x.bom_number.Equals(c.bom_number));
            foreach (var item in res)
            {
                item.bom_number = c.bom_number;
                item.bom_topic = c.bom_topic;
                item.remark = c.remark;
                item.default_bom = c.default_bom;
                //item.number_parts = c.number_parts;
                item.version_number = c.version_number;
                item.name_finished_product = c.name_finished_product;
                item.finished_number = c.finished_number;
                item.daily_output = c.daily_output;
            }
            var list = await bom_Management_TableRepository.UpdInfor_Batch_Async(res);
            if (list > 0)
            {
                apiReturn.Code = 200;
                apiReturn.Message = "修改成功!";
            }
            return apiReturn;
        }

        /// <summary>
        /// 反填BOM信息
        /// </summary>
        /// <param name="bom_number">BOM编号</param>
        /// <returns>BOM数据</returns>
        public async Task<bom_management_table> Getbackfill(string? bom_number)
        {
            Expression<Func<bom_management_table, bool>> wherename = x => x.bom_number == bom_number;
            var list = await bom_Management_TableRepository.GetShowObjAsync(wherename);

            return list;
        }



    }
}
